/**
 * 剑指 Offer 50. 第一个只出现一次的字符
 * https://leetcode-cn.com/problems/di-yi-ge-zhi-chu-xian-yi-ci-de-zi-fu-lcof/
 */

const codeA = 'a'.charCodeAt(0);

/**
 * @param {string} s
 * @return {string}
 */
function firstUniqChar(s) {
  const cache = new Array(26).fill(-1);
  for (let i = 0; i < s.length; i += 1) {
    const code = s.charCodeAt(i) - codeA;
    if (cache[code] >= 0) {
      cache[code] = -2;
    } else if (cache[code] === -1) {
      cache[code] = i;
    }
  }
  let min = -1;
  let minCode = -1;
  for (let i = 0; i < 26; i += 1) {
    if (cache[i] >= 0) {
      if (min < 0 || cache[i] < min) {
        min = cache[i];
        minCode = i;
      }
    }
  }
  if (minCode >= 0) {
    return String.fromCharCode(minCode + codeA);
  }
  return ' ';
}

console.log(firstUniqChar('') === ' ');
console.log(firstUniqChar('abaccdeff') === 'b');
console.log(firstUniqChar('aabb') === ' ');
